package com.smt.modules.bus.service.impl;

import com.smt.common.enums.Code;
import com.smt.common.utils.*;
import com.smt.modules.bus.entity.ProjectTaskEntity;
import com.smt.modules.bus.entity.SubtaskEntity;
import com.smt.modules.bus.service.ProjectService;
import com.smt.modules.bus.service.ProjectTaskService;
import com.smt.modules.bus.service.SubtaskService;
import com.smt.modules.bus.vo.ProjectTaskVo;
import com.smt.modules.bus.vo.ScheduleVo;
import com.smt.modules.bus.vo.SubtaskVo;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.smt.modules.bus.dao.ScheduleDao;
import com.smt.modules.bus.entity.ScheduleEntity;
import com.smt.modules.bus.service.ScheduleService;


@Service("scheduleService")
public class ScheduleServiceImpl extends ServiceImpl<ScheduleDao, ScheduleEntity> implements ScheduleService {

    @Autowired
    private ProjectTaskService projectTaskService;
    @Autowired
    private SubtaskService subtaskService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ScheduleEntity> page = this.selectPage(
                new Query<ScheduleEntity>(params).getPage(),
                new EntityWrapper<ScheduleEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新建日历
     *
     * @param schedule
     * @param userId
     * @return
     */
    @Override
    public R save(ScheduleVo schedule, Long userId) {
        Long projectId = schedule.getProjectId();
        if(Objects.isNull(projectId)){
            return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL),"项目id不能为空！");
        }
        schedule.setCreatedId(userId);
        schedule.setCreateTime(DateTime.now().toDate());
        schedule.setUpdateTime(DateTime.now().toDate());
        StringBuffer ids = new StringBuffer();
        List<Long> pIds = schedule.getPIds();
        if (pIds.size() == 0) {
            return R.error(EnumToKeyUtil.toInt(Code.REQUEST_PARAM_EMPTY),"参与人不能为空！");
        }
        pIds.stream().forEach(p -> {
            ids.append(p.longValue() + ",");
        });
        schedule.setParticipants(ids.toString());
        boolean insert = insert(schedule.copyPropertiesTo(new ScheduleEntity()));
        return insert ? R.ok("新建日历成功") :
                R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR), "新建日历失败");

    }

    /**
     * 获取事件详细信息
     *
     * @param id
     * @return
     */
    @Override
    public R info(Long id) {
        StringToListUtil stu = new StringToListUtil();
        ScheduleEntity scheduleEntity = selectById(id);
        String participants = scheduleEntity.getParticipants();
        List encode = stu.encode(Long.class, participants);
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("entity", scheduleEntity);
        map.put("pIds", encode);
        return R.ok().put("info", map);
    }


    /**
     * 获取多个成员日程表
     *
     * @param userIds
     * @return
     */
    @Override
    public R memberSchedules(List<Long> userIds, Long projectId, String date) {
        List<ScheduleEntity> schedules = baseMapper.selectSchedules(projectId);
        //日常日程集合
        schedules.stream().forEach(s -> {
            //更新其项目日程
            Long taskId = s.getTaskId();
            Long subTaskId = s.getSubTaskId();
            //单向的修改日程的标题,参与人
            if(!Objects.isNull(taskId)){
                ProjectTaskEntity projectTaskEntity =
                        projectTaskService.selectById(taskId);
                s.setTitle(projectTaskEntity.getTaskName());
                s.setParticipants(projectTaskEntity.getMemberId()+",");
            }else if(!Objects.isNull(subTaskId)){
                SubtaskEntity subtaskEntity =
                        subtaskService.selectById(subTaskId);
                s.setParticipants(subtaskEntity.getMemberId()+",");
                s.setTitle(subtaskEntity.getSubtaskName());
            }
        });
        List<ScheduleEntity> schedulesCopy = new CopyOnWriteArrayList<>();
        //日期筛选
        userIds.stream().forEach(u -> {
            schedules.stream().forEach(s -> {
                String participants = s.getParticipants();
                Date scheduleTime = s.getScheduleTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss");
                String format = sdf.format(scheduleTime);
                String month = format.split(" ")[0];
                month = month.substring(0,month.lastIndexOf("-"));
                if (StringUtils.contains(participants, String.valueOf(u))) {
                    if (month.equals(date)) {
                        schedulesCopy.add(s);
                    }
                }
            });
        });
        schedulesCopy.stream().forEach(e -> {
            String participants = e.getParticipants();
            StringToListUtil<Long> stringToListUtil = new StringToListUtil<>();
            List<Long> encode = stringToListUtil.encode(Long.class, participants);
            e.setPIds(encode);
        });
        return R.ok().put("schedules", schedulesCopy);
    }

    /**
     * 假删除
     *
     * @param id
     * @return
     */
    @Override
    public R deleteSchedules(Long id,Long userId) {
        int i = 0;
        ScheduleEntity scheduleEntity = selectById(id);
        if(scheduleEntity.getTaskId() != null || scheduleEntity.getSubTaskId() != null){
            return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL), "您无法修改项目日程！");
        }
        if(scheduleEntity.getCreatedId().equals(userId)){
             i = baseMapper.updateSchedules(id);
        }
        return i == 0 ? R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL), "您的权限不够！") : R.ok();
    }

    /**
     * 修改日程
     *
     * @param schedule
     * @return
     */
    @Override
    public R updateEvent(ScheduleVo schedule,Long userId) {
        if(schedule.getTaskId() != null || schedule.getSubTaskId() != null){
            return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL), "您无法修改项目日程！");
        }
        Long cId = schedule.getCreatedId();
        //数组 -> 字符串
        if(cId.equals(userId)){
            StringBuffer ids = new StringBuffer();
            schedule.getPIds().stream().forEach(s -> ids.append(s + ","));
            schedule.setParticipants(ids.toString());
            schedule.setUpdateTime(DateTime.now().toDate());
            boolean b = updateById(schedule.copyPropertiesTo(new ScheduleEntity()));
            return b ? R.ok("修改日程成功") :
                    R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR), "修改日程失败");
        }else{
            return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL), "您的权限不够！");
        }
    }


    /**
     * 添加任务和子任务的对应的日程
     *
     * @param scheduleInfo
     */
    @Override
    public void addScheduleInfo(Object scheduleInfo) {
        SubtaskVo subtaskVo = null;
        Long subTaskId = null;
        ProjectTaskVo projectTaskVo = null;
        Long projectTaskId = null;
        ScheduleEntity scheduleEntity = null;
        if(scheduleInfo instanceof SubtaskVo){
            subtaskVo =(SubtaskVo)scheduleInfo;
            subTaskId = subtaskVo.getId();
            scheduleEntity = selectOne(new EntityWrapper<ScheduleEntity>()
                    .eq("sub_task_id", subTaskId));
            SubtaskEntity subtaskEntity1 = subtaskService.selectById(subTaskId);
            ProjectTaskEntity project = projectTaskService.selectById(subtaskEntity1.getProjectTaskId());
            ScheduleEntity schedule = new ScheduleEntity(subtaskEntity1.getMemberId(),subtaskEntity1.getSubtaskName(),
                    subtaskVo.getEndTime(),0,subtaskEntity1.getSubtaskBreif(),DateTime.now().toDate()
                    ,DateTime.now().toDate(),"#c80000",project.getProjectId(),null,subtaskEntity1.getId());
            if (scheduleEntity != null) {
                schedule.setParticipants(String.valueOf(subtaskEntity1.getMemberId()));
                schedule.setId(scheduleEntity.getId());
                updateById(schedule);
            } else {
                schedule.setParticipants(String.valueOf(subtaskEntity1.getMemberId()));
                insert(schedule);
            }
        }else if(scheduleInfo instanceof ProjectTaskVo){
            projectTaskVo = (ProjectTaskVo)scheduleInfo;
            projectTaskId = projectTaskVo.getId();
            scheduleEntity = selectOne(new EntityWrapper<ScheduleEntity>()
                    .eq("task_id", projectTaskId));
            ProjectTaskEntity projectTaskEntity1 = projectTaskService.selectById(projectTaskId);
            ScheduleEntity schedule = new ScheduleEntity(projectTaskEntity1.getMemberId(),projectTaskEntity1.getTaskName()
                    ,projectTaskVo.getEndTime(),0,projectTaskEntity1.getRemark(),DateTime.now().toDate()
                    ,DateTime.now().toDate(),"#c80000",projectTaskEntity1.getProjectId(),projectTaskId,null);
            if (scheduleEntity != null) {
                schedule.setParticipants(String.valueOf(projectTaskEntity1.getMemberId()));
                schedule.setId(scheduleEntity.getId());
                updateById(schedule);
            } else {
                //增加
                schedule.setParticipants(String.valueOf(projectTaskEntity1.getMemberId()));
                insert(schedule);
            }
        }
    }
}
